<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="用户账号" prop="userName">
        <el-input
          style="width: 140px"
          v-model.trim="queryParams.userName"
          placeholder="请输入用户账号"
          clearable
          @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          style="width: 140px"
          v-model.trim="queryParams.nickName"
          placeholder="请输入昵称"
          clearable
          @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="用户状态" prop="status">
        <el-select
          style="width: 140px"
          v-model.trim="queryParams.status"
          placeholder="请选择用户状态"
          clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:add']">新增
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="userList" @expand-change="expandChange">
      <el-table-column label="用户ID" align="center" prop="userId" width="60"/>
      <el-table-column label="用户账号" align="center" prop="userName"/>
      <el-table-column label="昵称" align="center" prop="nickName"/>
      <el-table-column label="最近登录时间" align="center" prop="loginDate" width="100"/>
      <el-table-column label="注册区域" align="center" prop="areaCode"/>
      <el-table-column label="上级编号" align="center" prop="parentId" width="75"/>
      <el-table-column label="邀请用户" align="center" prop="inviteId" width="75"/>
      <el-table-column label="账号启用" align="center" width="75">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收入信息" align="center" type="expand" width="75">
        <template slot-scope="scope">
          <div>
            <el-row :gutter="4" type="flex" justify="end" style="margin-bottom: 8px">
              <el-col :span="6">支付宝提现姓名：{{ scope.row.alipayName }}</el-col>
              <el-col :span="6">支付宝提现账号：{{ scope.row.alipayAccount }}</el-col>
            </el-row>
            <el-row :gutter="2" type="flex" justify="end">
              <el-col :span="18">
                <el-table v-loading="incomeLoading" :data="incomeList">
                  <el-table-column label="ID" align="center" prop="id"/>
                  <el-table-column label="收入类型" align="center" prop="type"/>
                  <el-table-column label="收入金额" align="center" prop="amount"/>
                  <el-table-column label="当前状态" align="center" prop="status"/>
                  <el-table-column label="关联订单" align="center" prop="outId"/>
                  <el-table-column label="提现单号" align="center" prop="extractId"  width="110"/>
                  <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
                    <template slot-scope="scope">
                      <span>{{ parseTime(scope.row.updateTime, '{m}-{d} {h}:{m}:{s}') }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="140">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleResetPwd(scope.row)">重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"/>
    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户账号" prop="userName">
          <el-input v-model.trim="form.userName" placeholder="请输入用户账号（手机号）"/>
        </el-form-item>
        <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
          <el-input v-model.trim="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password/>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model.trim="form.nickName" placeholder="请输入昵称"/>
        </el-form-item>
        <el-form-item label="联系邮箱" prop="email">
          <el-input v-model.trim="form.email" placeholder="请输入用户邮箱"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listUser,
    changeUserStatus,
    getUser,
    delUser,
    addUser,
    updateUser,
    resetUserPwd
  } from "@/api/system/user";
  import {listByUserId} from "@/api/system/income";

  export default {
    name: "User",
    dicts: ['sys_normal_disable'],

    data() {
      return {
        userOptions: [],
        // 遮罩层
        loading: true,
        incomeLoading: true,
        // 总条数
        total: 0,
        // 用户信息表格数据
        userList: [],
        incomeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,

          userName: null,
          nickName: null,
          status: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          userName: [
            {required: true, message: "用户账号（手机号）不能为空", trigger: "blur"},
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ],
          password: [
            {required: true, message: "用户密码不能为空", trigger: "blur"},
            {min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur'},
            {pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur"}
          ],
          email: [
            {
              type: "email",
              message: "请输入正确的邮箱地址",
              trigger: ["blur", "change"]
            }
          ]
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      expandChange(row, expandedRows) {
        // 该处是用于判断是展开还是收起行，只有展开的时候做请求，避免多次请求！
        // 展开的时候expandedRows有值，收起的时候为空.
        if (expandedRows.length > 0) {
          listByUserId(row.userId).then(res => {
            this.incomeList = res.data
            this.incomeLoading = false
          })
        } else {
          this.incomeLoading = true
        }
      },
      // 用户状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function () {
          return changeUserStatus({
            userId: row.userId,
            status: row.status
          });
        }).then(() => {
          this.$modal.msgSuccess("已" + text);
        }).catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
      },

      /** 查询用户信息列表 */
      getList() {
        this.loading = true;
        listUser(this.queryParams).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          userId: null,
          userName: null,
          password: null,
          nickName: null,
          email: null,

          remark: null,
          status: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加用户信息";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const userId = row.userId
        getUser(userId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改用户信息";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.userId != null) {
              updateUser(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addUser(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      handleResetPwd(r) {
        this.$prompt('请输入"' + r.userName + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          inputPattern: /^.{5,20}$/,
          inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
          inputValidator: (value) => {
            if (/<|>|"|'|\||\\/.test(value)) {
              return "不能包含非法字符：< > \" ' \\\ |"
            }
          },
        }).then(({value}) => {
          resetUserPwd(r.userId, value).then(response => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          })
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$modal.confirm('是否确认删除用户信息编号为"' + row.userId + '"的数据项？').then(function () {
          return delUser(row.userId);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      }
    }
  };
</script>
